跳到主要内容

NC4 判断链表中是否有环

https://www.nowcoder.com/practice/650474f313294468a4ded3ce0f7898b9

这题还是挺简单的,判断环使用快慢指针就行了

func hasCycle( head *ListNode ) bool {
if head == nil || head.Next == nil {return false}
slow, fast := head, head.Next
for fast != nil && fast.Next != nil {
if fast.Val == slow.Val {
return true
}

slow = slow.Next
fast = fast.Next.Next
}

return false
}